class Area {
    constructor(config) {
        this.el = config.el;
        this.src = config.src;
        this.width=config.width?config.width:'600';
        this.linecolor=config.linecolor?config.linecolor:'green';
        this.fillcolor=config.fillcolor?config.fillcolor:'rgba(0,255,0,0.5)';
        this.fillselectcolor=config.fillselectcolor?config.fillselectcolor:'rgba(255,255,0,0.5)';
        this.selectpointcolor=config.selectpointcolor?config.selectpointcolor:'red';
        this.createdom();
        this.init();
    }
    //初始化画板
    init() {
        this.canvas = document.getElementById(this.el+'_child');
        this.ctx = this.canvas.getContext('2d');
        this.cW;
        this.cH;
        this.typeArr=["rgba(255,0,0,0.5)",'rgba(0,255,0,0.5)','rgba(255,0,0,0.5)','rgba(0,255,0,0.5)'];
        this.curtype=0;
        this.dragarea=false;
        this.oldlines=[];
        this.lines=[];
        this.points=[];
        this.isdragpoint=false;
        this.img = new Image();
        this.loadimg();
    }
    createdom(){
    	var style = 'button{border:none;color:#fff;border-radius:5px;padding:5px;}'
    	$('style').append(style);
    	var dom = $('#'+this.el);
    	var canvas = `<canvas id="${this.el}_child" width="${this.width}">`;
    	dom.append(canvas);
    	var operate = `<div style="margin:5px;padding:5px;color:#fff;"><button style="margin-left:10px;background:#ff0000;" class="addtag" data-type="0">本侧应急道</button><button style="margin-left:10px; background:#00ff00;" class="addtag" data-type="1">本侧主道</button><button style="margin-left:10px; background:#ff0000;" class="addtag" data-type="2">对向应急道</button><button style="margin-left:10px; background:#00ff00;" class="addtag" data-type="3">对向主道</button><button class="btn-complete" style="margin-left:10px; background:#000;">完成</button></div>`;
    	dom.append(operate);

    }
    loadimg() {
    	let t=this;
        let img = this.img;
        let canvas = this.canvas;
        let ctx=this.ctx
        img.src = this.src;
        img.onerror=function(){
        	alert("图片加载失败，请检查路径");
        	return false;
        }
        img.onload = function() {
            t.imgW = img.width;
            t.imgH = img.height;
            let imgW = t.imgW;
            let imgH = t.imgH;
            canvas.height = canvas.width * imgH / imgW;
            t.cW = canvas.width;
            t.cH = canvas.height;
            let cH=t.cH;
            let cW=t.cW;
            let isdragpoint = false;
            ctx.drawImage(img, 0, 0, imgW, imgH, 0, 0, cW, cH);
            // 鼠标按下事件
            canvas.onmousedown = function(e) {
                e.preventDefault();
                let x = e.clientX;
                let y = e.clientY;
                if (e.button == 0) { //鼠标左键打点
                    var drag = t.checkdrag({ x: x, y: y }, t.lines);
                    //1.判断是不是拖动点
                    if(t.points.length==0){
	                    if (drag) {
	                        t.isdragpoint = true;
	                        t.dragpoint(drag)
	                        return false;
	                    }
                    }
                    // 判断是不是选择区域
                    if(t.lines.length>0&&t.points.length==0){
                    	var pointisin=false;
                    	t.chosedindex=-1;
                    	for(var i=0;i<t.lines.length;i++){
                    		pointisin=t.isInPolygon([x,y],t.lines[i].data);
                    		if(pointisin){
                    			t.chosedindex=i;
			                    //选中区域改变颜色
			                    t.painlines(t.lines, t.points);
			                    if(t.dragarea){//首次选中不拖动
				                    canvas.onmousemove=function(e){
				                    	t.movearea([x,y],e,t.lines,t.points)
				                    }
			                    }
			                    t.dragarea=true;
			                    return false;
                    		}
                    	}
                    }
                    if(t.chosedindex>=0){
                    	return false;
                    }
                    t.points.push([x, y]) //记录点
                    //画点
                    t.painlines(t.lines, t.points);
                    canvas.oncontextmenu = (e) => {
                        if (e.button == 2) {
                            e.preventDefault();
                            
                            if(t.chosedindex>=0){
                            	t.chosedindex=-1;
                            	t.dragarea=false;
                            }else{
	                            if (t.points.length > 1) {
	                            	var tmpline=[];
	                            	tmpline['type']=t.curtype;
	                            	tmpline['data']=t.points;
	                                t.lines.push(tmpline);
	                                t.points = [];

	                            } else if (t.points.length == 1) {
	                                t.points = [];
	                            } else {
	                                t.lines.pop();
	                            }
                            }
                            console.log(t.lines)
                            t.painlines(t.lines, t.points);
                        }
                    }

                    canvas.addEventListener('mousemove', function(e) {
                        if (t.points.length == 0) { return false; }
                        let mX = e.clientX;
                        let mY = e.clientY;
                        var lastpoint = t.points[t.points.length - 1];
                        t.painlines(t.lines, t.points);
                        ctx.beginPath();
                        ctx.moveTo(lastpoint[0], lastpoint[1]);
                        ctx.lineTo(mX, mY);
                        ctx.stroke();
                    })
                }
                

            }
            
            canvas.addEventListener('mouseup', function(e) {
            	if(t.chosedindex>=0){
            		// t.chosedindex=-1;
            	}
            	t.isdragpoint=false;
                // t.painlines(t.lines, t.points);
                if(t.dragarea&&t.oldlines.length>0){
                	t.lines=t.oldlines;
                	t.painlines(t.lines, t.points);
                	canvas.onmousemove=function(){};
                }
            })

            canvas.onmousewheel = function(e) {
                e.preventDefault();
                console.log(e)
            }
        }

        $('.btn-complete').click(function(){
        	t.complete();
        })
        $('.addtag').click(function(){
        	t.curtype = $(this).data('type');
        })
    }
    //添加标签
    addtag(txt){
    	let ctx = this.ctx;
    	var text = ctx.measureText("foo");
    	ctx.fillStyle='yellow';
    	ctx.fillText(txt, 10, 50);
    }
    //移动区域
    movearea(point,e,lines,points){
    	let t=this;
    	let offsetX = e.clientX-point[0];
    	let offsetY = e.clientY-point[1];
    	var tmp = [];
    	lines.forEach(function(v,k){
    		tmp[k]=[];
    		tmp[k]['type']=v.type;
			tmp[k]['data']=[];
    		v.data.forEach(function(vv,kk){
    			tmp[k]['data'][kk]=[];
    			vv.forEach(function(vvv,kkk){
    				tmp[k]['data'][kk][kkk]=vvv;
    			})
    		})
    	})
    	tmp[t.chosedindex].data.forEach(function(v,k){
    		v[0] += offsetX;
    		v[1] += offsetY;
    	})
    	t.oldlines=tmp;
    	t.painlines(tmp,[]);
    }
    //拖动点
    dragpoint(point) {
        let t = this;
        t.painlines(t.lines, t.points, t.lines[point[0]].data[point[1]]);

        t.canvas.onmousemove = function(e) {
            if (t.isdragpoint) {
                t.lines[point[0]].data[point[1]] = [e.clientX, e.clientY];
                t.painlines(t.lines, t.points, t.lines[point[0]].data[point[1]]);
            }
        }

    }
    //绘制每条线
    painlines(lines, points, dragpoint = [],choseindex=-1) {
    	let t = this;
    	let ctx = this.ctx;
    	let img = this.img;
    	ctx.clearRect(0, 0, t.cW, t.cH);
        ctx.drawImage(img, 0, 0, t.imgW, t.imgH, 0, 0, t.cW, t.cH);
        // 已经选好的区域
        lines.forEach(function(item, index) {
            item.data.forEach(function(v, k) {
                ctx.beginPath();
                if (dragpoint.length == 2 && dragpoint[0] == v[0] && dragpoint[1] == v[1]) {
                    ctx.fillStyle = t.selectpointcolor;
                } else {
                    ctx.fillStyle = t.typeArr[item.type];
                }
                ctx.moveTo(v[0], v[1]);
                ctx.arc(v[0], v[1], 5, 0, Math.PI * 2);
                ctx.fill();
            })
            ctx.beginPath();
            ctx.strokeStyle = t.typeArr[item.type];
            ctx.lineWidth = 1;
            if(t.chosedindex>=0&&index==t.chosedindex){
            	ctx.fillStyle = t.fillselectcolor;
            }else{
            	ctx.fillStyle = t.typeArr[item.type];
            }
            
            item.data.forEach(function(v, k) {
                if (k == 0) {
                    ctx.moveTo(v[0], v[1]);
                } else {
                    ctx.lineTo(v[0], v[1]);
                }
            })
            ctx.lineTo([item.data][0][0], [item.data][0][1]);
            ctx.fill();
            ctx.stroke();
        })
        // 正在选的区域
        points.forEach(function(v, k) {
            ctx.beginPath();
            ctx.fillStyle = t.typeArr[t.curtype];
            ctx.moveTo(v[0], v[1]);
            ctx.arc(v[0], v[1], 5, 0, Math.PI * 2);
            ctx.fill();
        })
        ctx.beginPath();
        ctx.strokeStyle = t.typeArr[t.curtype];
        ctx.lineWidth = 3;
        points.forEach(function(v, k) {
            if (k == 0) {
                ctx.moveTo(v[0], v[1]);
            } else {
                ctx.lineTo(v[0], v[1]);
            }
            if (k == (points.length - 1)) {
                ctx.stroke();
            }
        })
    }
    // 检测是否点击在节点上
    checkdrag(point, lines) {
        if (lines.length == 0) {
            return false;
        }
        for (var i = 0; i < lines.length; i++) {
            var tmp = lines[i].data;
            for (var j = 0; j < tmp.length; j++) {
                if ((point.x - tmp[j][0]) * (point.x - tmp[j][0]) + (point.y - tmp[j][1]) * (point.y - tmp[j][1]) <= 100) {
                    return [i, j];
                }
            }
        }
        return false;
    }
    // 检测点击点是否在图形内部
    isInPolygon(checkPoint, polygonPoints) {
	    var counter = 0;
	    var i;
	    var xinters;
	    var p1, p2;
	    var pointCount = polygonPoints.length;
	    p1 = polygonPoints[0];
	 	
	    for (i = 1; i <= pointCount; i++) {
	        p2 = polygonPoints[i % pointCount];
	        if (
	            checkPoint[0] > Math.min(p1[0], p2[0]) &&
	            checkPoint[0] <= Math.max(p1[0], p2[0])
	        ) {
	            if (checkPoint[1] <= Math.max(p1[1], p2[1])) {
	                if (p1[0] != p2[0]) {
	                    xinters =
	                        (checkPoint[0] - p1[0]) *
	                            (p2[1] - p1[1]) /
	                            (p2[0] - p1[0]) +
	                        p1[1];
	                    if (p1[1] == p2[1] || checkPoint[1] <= xinters) {
	                        counter++;
	                    }
	                }
	            }
	        }
	        p1 = p2;
	    }
	    if (counter % 2 == 0) {
	        return false;
	    } else {
	        return true;
	    }
	}
}